﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.presentation;
using System.Security.Cryptography;
using legacy;
using System.Xml.XPath;
using System.Xml.Linq;
using umbraco.BusinessLogic;
using System.Web;
using umbraco;
using Core.Module.Interfaces.Model;
using System.Xml;
using Core.Module.Model;

namespace Core.Module
{
    [XsltExtension("site.library")]
    public class XsltExtention
    {
        public static bool IsCanvas()
        {
            return UmbracoContext.Current.LiveEditingContext.Enabled;
        }
        public string GetImageUrl(string imageid, string defaultvalue)
        {
            if (string.IsNullOrEmpty(imageid)) return defaultvalue;
            int imgid;
            if (!int.TryParse(imageid, out imgid) || imgid < 0) return defaultvalue;
            return umbraco.library.GetMedia(imgid, false).Current.SelectSingleNode("*/umbracoFile").InnerXml;
        }
        public static string ComputeHashString(string value)
        {
            string result = string.Empty;
            HashAlgorithm a = SHA512.Create();
            if (a != null)
            {
                byte[] values = ASCIIEncoding.UTF8.GetBytes(value);
                byte[] results = a.ComputeHash(values);

                StringBuilder hexString = new StringBuilder();
                foreach (Byte b in results)
                    hexString.Append(b.ToString("X2"));

                result = hexString.ToString();
            }
            return result;
        }
        public static string EncryptString(string TextToBeEncrypted)
        {

            string EncryptedData = RSACryptExtention.Encrypt(TextToBeEncrypted);
            return EncryptedData;
        }

        public static string DecryptString(string TextToBeDecrypted, string Password)
        {
            if (string.IsNullOrEmpty(Password)) Password = "abc123!";
            string DecryptedData = RSACryptExtention.Decrypt(TextToBeDecrypted);
            return DecryptedData;
        }
        /// <summary>
        /// Needs to transform text string to an XML iterator
        /// </summary>
        public static XPathNodeIterator TextToXMLIterator(string data)
        {
            data = string.IsNullOrEmpty(data) ? "<empty/>" : data;
            XDocument xd = null;
            try
            {
                xd = XDocument.Parse(HttpUtility.HtmlDecode(data));
            }
            catch (Exception ex)
            {
                xd = XDocument.Parse("<data/>");
                xd.Element("data").Add(new XElement("error", ex.Message));
                xd.Element("data").Add(new XElement("text", data));
                Log.Add(LogTypes.Error, -1, "XslEx:can't transf.data:" + ex.Message);
            }
            return xd.CreateNavigator().Select(".");
        }
        /// <summary>
        /// needs to return one value depends of first param: if it true then first value otherwise second
        /// </summary>        
        public static string ShortIf(bool check, string trueValue, string falseValue)
        {
            return check ? trueValue : falseValue;
        }
        /// <summary>
        /// needs to return one value depends of first param: if it true then first value otherwise second
        /// </summary>        
        public static XPathNodeIterator ShortIfNodes(bool check, XPathNodeIterator trueValue, XPathNodeIterator falseValue)
        {
            return check ? trueValue : falseValue;
        }

        public static string LowerCase(string text)
        {
            return string.IsNullOrEmpty(text) ? "" : text.ToLowerInvariant();
        }

        public static bool IsIn(string nodeId, string nodeIdSet)
        {
            int intNodeId;
            if (!int.TryParse(nodeId, out intNodeId))
                return false;
            return nodeIdSet.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(nodeId)
                ? true
                : false;
        }

        public static string ReplaceText(string text, string replaceFrom, string replaceTo)
        {
            return (text ?? "").Replace(replaceFrom, replaceTo);
        }

        public static string FormatDate(string date, string format)
        {
            DateTime dtime = DateTime.Now;
            if (DateTime.TryParse(date, out dtime))
            {
                if (format == "dayofweek") date = ((int)dtime.DayOfWeek).ToString();
                else date = dtime.ToString(format);
            }
            else date = "wrong:" + date;
            return date;
        }

        public static string DivCeiling(string dividend, string divisor)
        {
            double nr1, nr2;
            if (double.TryParse(dividend, out nr1) && double.TryParse(divisor, out nr2))
            {
                return ((int)Math.Ceiling(nr1 / nr2)).ToString();
            }
            return "wrong number";
        }

        public static string Random(string length)
        {
            Random r = new Random();
            Int64 min = Convert.ToInt64(Math.Pow(10, Int32.Parse(length) - 1));
            Int64 max = Convert.ToInt64(Math.Pow(10, Int32.Parse(length)));
            return Convert.ToInt64(r.NextDouble() * max).ToString();
            //return r.Next(min, max).ToString();
        }


        #region Module system
        public static XPathNodeIterator CurrentPage()
        {
            return umbraco.library.GetXmlNodeCurrent();
        }
        public static XPathNodeIterator PageSite(string id)
        {
            IModuleNode cnode = Context.Frontend.Nodes.Get(id);
            Site site = cnode == null ? null : Context.Frontend.Sites.Get(cnode.SiteId) as Site;
            if (site == null) return umbraco.library.GetXmlNodeById("-1");
            XmlDocument  xd=new XmlDocument();
            xd.LoadXml(site.ToXml());
            return xd.CreateNavigator()
                .Select("/*");
        }
        public static string GetLinkLists(string siteid)
        {
            ISite site=Context.Frontend.Sites.Get(siteid);
             
            IModuleNode allLinksLists=Context.Frontend.Nodes.GetChild(site.Settings.Id, "LinkListArea");
            if (allLinksLists== null) return null;
            return allLinksLists.Id;
        }
        #endregion
    }
}
